<template>
  <div class="eng_table">
    <el-table ref="table" :data="tdata" size="small" style="width: 100%; text-align: center" height="450">
      <el-table-column prop="engineerType" label="工程师类型" align="center">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.engineerType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="engineerLevel" label="工程师等级" align="center">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.engineerLevel }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="engineerCost" label="工程师工时费">
        <template slot-scope="scope">
          <el-input v-model="scope.row.engineerCost" size="small" :readonly="isView" @change="handleEdit(scope.$index, scope.row)" @keyup.native="oninput(scope.$index, scope.row)" />
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  props: {
    isView: {
      type: Boolean,
      required: true
    },
    data: {
      type: Array,
      default: new Array(0)
    }
  },
  data() {
    return {
      tdata: this.data
    }
  },
  watch: {
    tdata(val, oldVal) {
      console.log('tdata:', val, oldVal);
    },
    data(val, oldVal) {
      console.log('data', val, oldVal);
      this.tdata = val;
    }
  },
  mounted: function() {
    console.log(1);
    console.log(this.data);
  },
  methods: {
    handleEdit(index, data) {
      console.log(data);
      this.data[index] = data;
    },
    oninput(index, data) {
      console.log(data);
      let str = this.data[index]['engineerCost']
      const len1 = str.substr(0, 1)
      const len2 = str.substr(1, 1)
      // 如果第一位是0，第二位不是点，就用数字把点替换掉
      if (str.length > 1 && len1 === 0 && len2 !== '.') {
        str = str.substr(1, 1)
      }
      // 第一位不能是.
      if (len1 === '.') {
        str = ''
      }

      // 正则替换
      str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点

      // 限制只能输入一个小数点
      if (str.indexOf('.') !== -1) {
        const str_ = str.substr(str.indexOf('.') + 1)
        if (str_.indexOf('.') !== -1) {
          str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
        }
        if (str_.length > 2) {
          str = str.substr(0, str.indexOf('.') + 1) + str_.substr(0, 2)
        }
      }
      // str = str.replace(/\.\d\d\d$/,'') // 小数点后只能输两位
      this.data[index]['engineerCost'] = str
    }
  }
}
</script>

<style lang="scss">
.eng_table {
  .el-table--small th, .el-table--small td {
    padding: 5px 0;
  }
  .el-table th.is-leaf, .el-table td {
    border: none;
  }
}
</style>
